package com.tansun.easycare.rule.datamodel.web;


import java.io.Serializable;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.exception.ExceptionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONArray;
import com.github.pagehelper.PageInfo;
import com.tansun.easycare.core.utils.ResponseTable;
import com.tansun.easycare.core.utils.StringUtils;
import com.tansun.easycare.rule.common.DataCache;
import com.tansun.easycare.rule.common.JsonMessage;
import com.tansun.easycare.rule.common.ResMessage;
import com.tansun.easycare.rule.common.RuleBaseController;
import com.tansun.easycare.rule.datamodel.entity.RuleDataEntity;
import com.tansun.easycare.rule.datamodel.entity.RuleDataset;
import com.tansun.easycare.rule.datamodel.model.DataSourceView;
import com.tansun.easycare.rule.datamodel.service.DBtoDataModelService;
import com.tansun.easycare.rule.datamodel.service.impl.DataModelServiceImpl;
import com.tansun.easycare.rule.datasource.entity.RuleDatasheet;
import com.tansun.easycare.rule.datasource.entity.RuleDatasheetColumn;
import com.tansun.easycare.rule.datasource.service.RuleDatasheetColumnService;
import com.tansun.easycare.rule.datasource.service.RuleDatasourceService;
import com.tansun.easycare.rule.front.entity.RuleDatasource;


/**
 * 导入表Controller
 *
 * @author ypx
 * @version 2018-08-09
 */
@Controller
@RequestMapping(value ="/ruleProj/dataModel/dbtoDataModel")
public class DBtoDataModelController extends RuleBaseController {
	private final Logger log = LoggerFactory.getLogger(this.getClass());
	
	@Autowired
	private DBtoDataModelService dbtoDataModelService;
	
	@Autowired
	private DataModelServiceImpl dataModelService;
	
	@Autowired
	private RuleDatasourceService datasourceService;
	@Autowired
	private RuleDatasheetColumnService colService;
	
	@RequestMapping("dbform")
	@ResponseBody
	public DataSourceView form(RuleDatasheet entity,String rankRelationId,String projectCode,String modelName,Model model,ModelMap map) throws Exception {
		DataSourceView view = new DataSourceView();
		view.setDatasources(datasourceService.findList(new RuleDatasource()));
		view.setEntity(entity);
		if(entity!=null && StringUtils.isNotBlank(entity.getId())){
			RuleDatasheetColumn col = new RuleDatasheetColumn();
			col.setDatasheetId(entity.getId());
			view.setCols(colService.findList(col));
		}
		if (StringUtils.isEmpty(projectCode)) {
	            projectCode =this.getCurrProjectCode();
	    }
		view.setDatasetList(dataModelService.getDataModelListByProjectCode(projectCode, modelName));
		return view;
	}

	/**
	 * 根据数据源ID，获取数据源下所有表名称
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "getDbTable")
	@ResponseBody
	public JsonMessage getDbTable(String id) {
		JsonMessage result = new JsonMessage();
		try {
			RuleDatasource ruleDatasource = datasourceService.get(id);
			List<RuleDatasheet> list = dbtoDataModelService.findDbTable(ruleDatasource);
			result.setData((Serializable) list);
		} catch (Exception e) {
			log.error("获取数据库表出错",e);
			result.setResult(false);
		}
		
		return result;
	}
	
	/**
	 * 获取数据库表的列信息
	 * @param entity
	 * @return
	 */
	@RequestMapping(value = "getTableCol")  
	@ResponseBody
	public ResponseTable<RuleDatasheetColumn> getTableCol(RuleDatasheet entity) {
		ResponseTable<RuleDatasheetColumn> rst = new ResponseTable<>();
		try {
			List<RuleDatasheetColumn> list = dbtoDataModelService.findTableCols(entity);
			PageInfo<RuleDatasheetColumn> pageInfo = new PageInfo();
            pageInfo.setPageNum(1);
            pageInfo.setPageSize(10);
            pageInfo.setSize(list.size());
            pageInfo.setStartRow(1);
            pageInfo.setEndRow(list.size());
            pageInfo.setTotal(list.size());
            pageInfo.setPages(1);
            pageInfo.setPrePage(0);
            pageInfo.setNextPage(0);
            pageInfo.setIsFirstPage(true);
            pageInfo.setIsLastPage(true);
            pageInfo.setHasPreviousPage(false);
            pageInfo.setHasNextPage(false);
            pageInfo.setNavigatePages(8);
            pageInfo.setNavigateFirstPage(1);
            pageInfo.setNavigateLastPage(1);
            pageInfo.setNavigatepageNums(new int[]{1});
            pageInfo.setList(list);
		} catch (Exception e) {
			e.printStackTrace();
			log.error("获取列信息出错",e);
            logger.debug(ExceptionUtils.getStackTrace(e));
		}
		return rst;
	}
	
	
    @RequestMapping(value = "getOpenList")
    public String getOpenList() {
    	return "rule/datamodel/dbgentable/openData";
    }
    
    /**
     * 数据查询时获取数据模型列表
     *
     * @param projectCode 规则项目编码
     * @param modelName   数据模型编码（固定取dataModel）
     * @return 数据模型json串
     */

    @RequestMapping("getJsonArray")
    @ResponseBody
    public String getJsonArray(HttpServletRequest request, HttpServletResponse response, String projectCode, String modelName,ModelMap map) throws Exception {
        ResMessage msg = null;
        List<RuleDataset> list;
        try {
            projectCode = getCurrProjectCode();
            list = dataModelService.getDataModelListByProjectCode(projectCode, modelName);
        } catch (Exception e) {
            msg = new ResMessage("failure", "获取数据失败");
            logger.debug(ExceptionUtils.getStackTrace(e));
            return JSONArray.toJSONString(msg);
        }
        return JSONArray.toJSONString(list);
    }
    
    /**
     * 保存数据集
     */
    @RequestMapping(value = "save")
    public @ResponseBody
    JsonMessage save(@RequestBody RuleDataEntity RuleDataEntity,String projectCode) {
        JsonMessage ret = new JsonMessage();
        try {
        	projectCode = super.getCurrProjectCode();
            dbtoDataModelService.saveOrUpdate(RuleDataEntity);
        	DataCache.paramChange(projectCode);
            ret.setMessage("保存数据模型成功");
        } catch (Exception e) {
        	e.printStackTrace();
        	ret.setResult(false);
            ret.setMessage(e.getMessage());
        } 
       
        return ret;
    }

	
    
    
  
}
	
	